from django.shortcuts import render
from django.shortcuts import redirect
from .models import Books


# 默认首页, 列出表中所有数据
def book_index(request):
    books = Books.objects.all()
    print(books)
    return render(request, 'book/index.html', {'books': books})


# 添加图书
def book_add(request):
    if request.method == 'GET':
        return render(request, 'book/book_add.html')
    else:
        book_name = request.POST.get('book_name')
        book_author = request.POST.get('book_author')
        book_price = request.POST.get('book_price')
        book = Books()
        book.name = book_name
        book.author = book_author
        book.price = float(book_price)
        print(book_name)
        print(book_author)
        print(book_price)
        book.save()
        return redirect('book_index')


# 图书详情
def book_detail(request, book_id):
    book = Books.objects.get(id=book_id)
    print(book)
    return render(request, 'book/book_detail.html', {'book': book})


# 删除图书
def book_delete(request):
    if request.method == 'POST':
        book_id = request.POST.get('book_id')
        book = Books.objects.get(id=book_id)
        print(book)
        book.delete()
        return redirect('book_index')
    else:
        raise RuntimeError("删除图书错误")


# 编辑图书详情
def book_edit(request, book_id):
    if request.method == 'GET':
        book = Books.objects.get(id=book_id)
        print(book)
        return render(request, 'book/book_edit.html', {"book": book})
    else:
        book = Books.objects.get(id=book_id)
        book_name = request.POST.get('book_name')
        book_author = request.POST.get('book_author')
        book_price = request.POST.get('book_price')
        book.name = book_name
        book.author = book_author
        book.price = float(book_price)
        book.save()
        print(book_name)
        print(book_author)
        print(book_price)
        return redirect('book_index')
